package com.xiaobo.androidaidl;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    public static String TAG = MainActivity.class.getSimpleName();

    private IUserAidlInterface iMyAidlInterface;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btnBindService).setOnClickListener(v -> {
                    intent = new Intent(MainActivity.this, UserService.class);
                    bindService(intent, connection, BIND_AUTO_CREATE);
                }
        );

        findViewById(R.id.btnUnBindService).setOnClickListener(v -> {
           unbindService(connection);
        });

        findViewById(R.id.btnInVoke).setOnClickListener(v -> {
            if(iMyAidlInterface != null){
                try {
                    iMyAidlInterface.printUser("user");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        findViewById(R.id.btnCusType).setOnClickListener(v -> {
            if(null != iMyAidlInterface){
                try {
                    User user = iMyAidlInterface.getUser();
                    Log.i(TAG, user.getUserName());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e(TAG, "onServiceConnected");
            iMyAidlInterface = IUserAidlInterface.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG, "onServiceDisconnected");

        }
    };
}


